package com.zhaoyh.framework.code.util;



import com.zhaoyh.transport.tio.showcase.websocket.server.ShowcaseWebsocketStarter;

import javax.servlet.ServletContext;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author 祥霸
 * @date 2019/2/22
 */
public class WebContextUtil{
    public static String HOST_NAME = null;

    public static String serverHostname = "pc2";// pc2

    public static boolean IS_PROD_SERVER = false;

    public static ServletContext servletContext = null;

    public static String ctx = null;

    public static String basePath = null;

    public static String classPath = null;

    public static void init(ServletContext _servletContext) {
        servletContext = _servletContext;
        basePath = _servletContext.getRealPath("");
        classPath = File.separator + "WEB-INF" + File.separator + "classes" + File.separator;

        ctx = _servletContext.getContextPath();
        try {
            HOST_NAME = InetAddress.getLocalHost().getHostName();
            if (serverHostname.indexOf(HOST_NAME) != -1) {
                IS_PROD_SERVER = true;
                LogUtil.log.info("生产环境，Hostname：【" + HOST_NAME + "】");
            } else {
                IS_PROD_SERVER = false;
                LogUtil.log.info("非生产环境，Hostname：【" + HOST_NAME + "】");
            }
        } catch (UnknownHostException e) {
            LogUtil.log.warn("主机名获取失败");
        }

        setAttribute("ctx", ctx);
        setAttribute("ggversion", System.currentTimeMillis());


        // socket
        if (!WebContextUtil.IS_PROD_SERVER) {
            try {
                ShowcaseWebsocketStarter.startP();
            } catch (Exception e) {
                LogUtil.log.info("----------------- websocket -------------- 启动异常");
            }
        }
    }

    /**
     * 设置全局session变量
     *
     * @param name
     * @param object
     */
    public static void setAttribute(String name, Object object) {
        servletContext.setAttribute(name, object);
    }


}
